package customerEnter.Frame.daoTransaction;

import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import customerEnter.Frame.JDBCDao.JdbcTemplate.IcyDataTemplate;
import customerEnter.Frame.Utils.Log4j;

/**
 * 
 * 类描述：
 * 
 * 类名称：IcyDataTemplateFactory
 * 
 * 创建人：dy
 * 
 * 创建时间：2017-7-27 下午1:51:23
 * 
 */
public class IcyDataTemplateFactory {

	IcyDataTemplate	icyDataTemplate;

	/**
	 * 如果当前线程存在Connection，就使用该Connection，否者开启一个新的Connection
	 * 
	 * @return
	 */
	public Connection getSession() {
		// 传入this，是因为，我们以当前factory类作为键保存的Connection
		if (TransactionSynchronizationManager.hasResource(this)) {
			return getCurrentSession();
		} else {
			return openSession();
		}
	}

	private Connection openSession() {
		Connection connection = getConnection();
		// 注册进当前线程管理一个Synchronization
		TransactionSynchronization transactionSynchronization = new IcyTransaction(this);
		TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
		// 绑定新开启的一个进当前线程事务管理器
		TransactionSynchronizationManager.bindResource(this, connection);
		return connection;
	}

	/**
	 * 获取当前线程的 connection
	 * 
	 * @return
	 */
	private Connection getCurrentSession() {
		Connection connection = (Connection) TransactionSynchronizationManager.getResource(this);
		try {
			if (connection.isClosed()) {
				TransactionSynchronizationManager.unbindResource(this);
				return openSession();
			}
		} catch (SQLException e) {
			Log4j.Log4JOutError(e.getMessage());
		}
		return connection;
	}

	public IcyDataTemplate getIcyDataTemplate() {
		return icyDataTemplate;
	}

	public void setIcyDataTemplate(IcyDataTemplate icyDataTemplate) {
		this.icyDataTemplate = icyDataTemplate;
	}

	public Connection getConnection() {
		Connection connection = null;
		try {
			connection = icyDataTemplate.getDataSource().getConnection();
		} catch (Exception e) {
		}
		return connection;
	}

}
